# coding = utf-8
import base64
import os
import time
from io import BytesIO

from django.http import HttpResponse

from wine import settings
from django.db.models import Q

from rest_framework import status, filters
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from shopping.models import GoodsImage, Goods, Category, GiftPackage
from users.api.utils import get_user_by_request

from .serializers import CategorySerializer, GoodsImageSerializer, GoodsSerializer, GiftPackageSerializer, \
    GoodsListSerializer


class GoodsListAPIView(ListAPIView):
    """商品列表"""
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = Goods.objects.filter(drop=0)
    serializer_class = GoodsListSerializer


class CategoryViewSet(ModelViewSet):
    """分类"""
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset


class GoodsViewSet(ModelViewSet):
    """商品"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        name = self.request.query_params.get("name", None)
        category = self.request.query_params.get("category", None)

        if category:
            queryset = queryset.filter(category_id=int(category))

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class GoodsImageViewSet(ModelViewSet):
    """商品图片"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = GoodsImage.objects.all()
    serializer_class = GoodsImageSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        goods_id = self.request.query_params.get("goods_id")

        if goods_id:
            queryset = queryset.filter(goods_id=goods_id)

        return queryset


class GoodsImageUploadAPIView(APIView):
    # authentication_classes = ()
    def post(self, request, *args, **kwargs):
        # 接收文件
        content_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/tiff']
        file = request.FILES.get('image', None)
        goods_id = request.data.get("goods_id", None)
        if file and file.content_type in content_types:
            print(file, goods_id)
            upload_path = GoodsImage.image.field.upload_to
            dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            file_info = file.name.rsplit(".", 1)
            old_file_name = file_info[0]
            file_suffix = file_info[1]
            file_name = '{0}_{1}.{2}'.format(old_file_name, int(time.time()), file_suffix)
            file_path = os.path.join(dirs, file_name)

            with open(file_path, 'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)

            file_url = '{0}{1}'.format(upload_path, file_name)
            data = {
                'goods_id': goods_id,
                'name': file.name,
                'image': file_url,
            }

            obj = GoodsImage.objects.create(**data)
            dict_obj = {
                "id":   obj.id,
                "name": obj.name,
                "goods_id": obj.goods_id,
                "image": "{}://{}{}".format(request.scheme, request.get_host(), obj.image.url),
            }

            msg = {
                "status_code": status.HTTP_200_OK,
                "file": dict_obj,
            }
            return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


class GoodsContentImageUploadAPIView(APIView):
    permission_classes = ()

    def post(self, request, *args, **kwargs):
        # 接收文件
        content_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/tiff']
        file = request.FILES.get('file', None)

        if file and file.content_type in content_types:
            # img_byte = base64.b64decode(file)
            # print(img_byte)
            upload_path = GoodsImage.image.field.upload_to
            dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            file_info = file.name.rsplit(".", 1)
            old_file_name = file_info[0]
            file_suffix = file_info[1]
            file_name = '{0}_{1}.{2}'.format(old_file_name, int(time.time()), file_suffix)
            file_path = os.path.join(dirs, file_name)

            with open(file_path, 'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)

            # image_data = open(file_path, "rb").read()

            # b_image_data = b'data:image/' + file_suffix.encode() +b';base64,' + base64.b64encode(image_data)
            # settings.DEBUG = False
            if settings.DEBUG:
                b_image_data = "{}://{}{}{}{}".format(request.scheme, request.get_host(), settings.MEDIA_URL, upload_path, file_name)
            else:
                b_image_data = "{}{}{}".format(settings.MEDIA_URL, upload_path, file_name)
            ret_data = {
                'file': b_image_data,
            }

            return Response(ret_data)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


class GiftPackageViewSet(ModelViewSet):
    """礼包"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = GiftPackage.objects.all()
    serializer_class = GiftPackageSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        user = get_user_by_request(self.request)
        if user is None:
            return queryset.none()

        name = self.request.query_params.get("name", None)
        category = self.request.query_params.get("category", None)
        print(name)
        if category:
            queryset = queryset.filter(category_id=int(category))

        if name:
            queryset = queryset.filter(Q(gift_name__contains=name) | Q(card_no=name))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)
